// 待办事项管理应用
class TodoApp {
    constructor() {
        this.todos = this.loadTodos();
        this.init();
    }

    // 初始化
    init() {
        this.render();
        this.updateStats();
    }

    // 从本地存储加载待办事项
    loadTodos() {
        const saved = localStorage.getItem('todos');
        return saved ? JSON.parse(saved) : [];
    }

    // 保存到本地存储
    saveTodos() {
        localStorage.setItem('todos', JSON.stringify(this.todos));
    }

    // 添加新的待办事项
    addTodo() {
        const input = document.getElementById('todoInput');
        const text = input.value.trim();
        
        if (text === '') {
            alert('请输入待办事项内容！');
            return;
        }

        const todo = {
            id: Date.now(),
            text: text,
            completed: false,
            createdAt: new Date().toISOString()
        };

        this.todos.unshift(todo);
        this.saveTodos();
        this.render();
        this.updateStats();
        
        input.value = '';
        input.focus();
    }

    // 删除待办事项
    deleteTodo(id) {
        if (confirm('确定要删除这个待办事项吗？')) {
            this.todos = this.todos.filter(todo => todo.id !== id);
            this.saveTodos();
            this.render();
            this.updateStats();
        }
    }

    // 切换完成状态
    toggleTodo(id) {
        const todo = this.todos.find(todo => todo.id === id);
        if (todo) {
            todo.completed = !todo.completed;
            this.saveTodos();
            this.render();
            this.updateStats();
        }
    }

    // 编辑待办事项
    editTodo(id, newText) {
        const todo = this.todos.find(todo => todo.id === id);
        if (todo && newText.trim() !== '') {
            todo.text = newText.trim();
            this.saveTodos();
            this.render();
        }
    }

    // 渲染待办事项列表
    render() {
        const todoList = document.getElementById('todoList');
        todoList.innerHTML = '';

        if (this.todos.length === 0) {
            todoList.innerHTML = `
                <div class="text-center text-muted py-5">
                    <i class="fas fa-inbox fa-3x mb-3"></i>
                    <p>暂无待办事项</p>
                </div>
            `;
            return;
        }

        this.todos.forEach(todo => {
            const todoItem = document.createElement('div');
            todoItem.className = `todo-item ${todo.completed ? 'completed' : ''}`;
            
            todoItem.innerHTML = `
                <input type="checkbox" ${todo.completed ? 'checked' : ''} 
                       onchange="todoApp.toggleTodo(${todo.id})">
                <span class="todo-text" data-id="${todo.id}" 
                      ondblclick="todoApp.startEdit(${todo.id}, this)">${this.escapeHtml(todo.text)}</span>
                <i class="fas fa-trash delete-btn" onclick="todoApp.deleteTodo(${todo.id})"></i>
            `;
            
            todoList.appendChild(todoItem);
        });
    }

    // 开始编辑
    startEdit(id, element) {
        const currentText = element.textContent;
        element.innerHTML = `<input type="text" class="form-control form-control-sm" 
                             value="${currentText}" 
                             onblur="todoApp.finishEdit(${id}, this.value)"
                             onkeypress="if(event.key === 'Enter') todoApp.finishEdit(${id}, this.value)">`;
        const input = element.querySelector('input');
        input.focus();
        input.select();
    }

    // 完成编辑
    finishEdit(id, newText) {
        this.editTodo(id, newText);
    }

    // 更新统计信息
    updateStats() {
        const total = this.todos.length;
        const completed = this.todos.filter(todo => todo.completed).length;
        const pending = total - completed;

        document.getElementById('totalCount').textContent = total;
        document.getElementById('completedCount').textContent = completed;
        document.getElementById('pendingCount').textContent = pending;
    }

    // HTML转义防止XSS
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 全局函数
function addTodo() {
    todoApp.addTodo();
}

// 初始化应用
const todoApp = new TodoApp();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    const input = document.getElementById('todoInput');
    input.focus();
});
